<template>
  <div>
    <editorLayout
      :title="$t('quickCreate.dot1xAll')"
      :isVisible="isVisible"
      @close="onClose"
    >
      <a-tabs
        v-model="activeKey"
        style="text-align: left"
        @change="onChangeTab"
      >
        <a-tab-pane :tab="$t('quickCreate.rule')" :key="1">
          <authForm
            formType="dot1xWired"
            :record="ruleForm"
            ref="authFormRef"
          ></authForm>
        </a-tab-pane>
        <a-tab-pane :tab="$t('quickCreate.source')" :key="2">
          <userSourceSelector
            ruleType="dot1x"
            :accountSourceIds="accountSourceIds"
            ref="userSourceSelectorRef"
          ></userSourceSelector>
        </a-tab-pane>
        <a-tab-pane :tab="$t('quickCreate.devGroup')" :key="3">
          <deviceGroupSelector
            ruleType="dot1x"
            :areaIds="areaIds"
            ref="deviceGroupSelectorRef"
          ></deviceGroupSelector>
        </a-tab-pane>
      </a-tabs>
      <div slot="foot" class="footer">
        <div class="btn-wrapper">
          <a-button @click="onClose">
            {{ $t('common.cancel') }}
          </a-button>
          <a-button type="primary" @click="onSave">
            {{ $t('common.save') }}
          </a-button>
        </div>
      </div>
    </editorLayout>
  </div>
</template>
<script>
import editorLayout from '@project/authSys/components/editorLayout';
import userSourceSelector from '@project/authSys/views/quickCreate/userSourceSelector';
import deviceGroupSelector from '@project/authSys/views/quickCreate/deviceGroupSelector';
import authForm from '@project/authSys/views/quickCreate/authForm';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import _ from 'lodash';
import { maccApi } from '@utils/index';
import { mapState } from 'vuex';
export default {
  name: 'dot1xWiredEditor',
  mixins: [authSysMixin],
  components: {
    editorLayout,
    authForm,
    userSourceSelector,
    deviceGroupSelector,
  },
  data() {
    return {
      activeKey: 1,
      previousKey: 1,
      isVisible: false,
      ruleForm: {},
      formRecord: null,

      // 编辑时使用
      accountSourceIds: [],
      areas: [],
      areaIds: [],

      userSources: [],
    };
  },
  mounted() {},
  computed: {
    ...mapState('AuthCommon', ['thirdPartSources']),
    nextBtnTxt() {
      if (this.currentStep === this.steps.length - 1) {
        return this.$t('quickCreate.confirmAdd');
      }
      return this.$t('common.next');
    },
  },
  methods: {
    async onSave() {
      // 为了防止直接保存的情况，这时后面两个还没有初始化为空
      let tempRuleForm = {
        ...this.ruleForm,
        tenantId: this.tenantInfo.tenantId,
        groupId: this.groupId,
      };

      const authModel = await this.$refs.authFormRef.getModel();
      if (!authModel) {
        return false;
      }
      tempRuleForm = { ...tempRuleForm, ...authModel };
      // tommy 240713 不切换tab直接保存时，后面两个Tab出现报错
      if (
        tempRuleForm.accountSourceList &&
        tempRuleForm.accountSourceList.length > 0
      ) {
        const accountSourceIds = [];
        for (const area of tempRuleForm.accountSourceList) {
          accountSourceIds.push(area.id);
        }
        tempRuleForm.accountSourceIds = accountSourceIds.join(',');
      }
      if (tempRuleForm.areaList && tempRuleForm.areaList.length > 0) {
        const areaIds = [];
        for (const area of tempRuleForm.areaList) {
          areaIds.push(area.id);
        }
        tempRuleForm.areaIds = areaIds.join(',');
      }

      if (this.$refs.userSourceSelectorRef) {
        const userSourceIds =
          await this.$refs.userSourceSelectorRef.getSelectedIds();
        if (userSourceIds.length === 0) {
          return false;
        }
        tempRuleForm.accountSourceIds = userSourceIds.join(',');
      }

      if (this.$refs.deviceGroupSelectorRef) {
        const deviceGroupIds =
          await this.$refs.deviceGroupSelectorRef.getSelectedIds();
        if (deviceGroupIds.length === 0) {
          return false;
        }
        tempRuleForm.areaIds = deviceGroupIds.join(',');
      }

      const res = await this.requestHttpAuth({
        api: maccApi.MACC_RULE_UPDATE_PUT_API,
        method: 'PUT',
        params: tempRuleForm,
      });

      if (res.data.success) {
        this.$message.success(this.$t('common.editSuccess'));
        this.$emit('refreshList');
        this.onClose();
      } else {
        this.$message.warning(res.data.message);
      }
    },

    async onChangeTab() {
      if (this.previousKey === 1) {
        const authModel = await this.$refs.authFormRef.getModel();
        if (!authModel) {
          this.$message.warning(this.$t('quickCreate.ruleComplete'));
          this.activeKey = this.previousKey;
          return false;
        }
        this.currentStep++;
      } else if (this.previousKey === 2) {
        const userSourceIds =
          await this.$refs.userSourceSelectorRef.getSelectedIds();
        if (!userSourceIds) {
          this.activeKey = this.previousKey;
          return false;
        }
        this.currentStep++;
      } else if (this.previousKey === 3) {
        const deviceGroupIds =
          await this.$refs.deviceGroupSelectorRef.getSelectedIds();
        if (!deviceGroupIds) {
          this.activeKey = this.previousKey;
          return false;
        }
        // this.onSave();
      }
      this.previousKey = this.activeKey;
    },

    getUserSourceList() {
      this.userSources = [
        {
          sourceId: -1,
          sourceType: 'account',
          sourceName: 'Local Account',
        },
        {
          sourceId: -2,
          sourceType: 'voucher',
          sourceName: 'Local Voucher',
        },
        {
          sourceId: -3,
          sourceType: 'mac',
          sourceName: 'Local MAC',
        },
      ];
      for (const source of this.thirdPartSources) {
        this.userSources.push({
          sourceId: source.id,
          sourceType: source.type,
          sourceName: source.name,
        });
      }
    },

    openEditor(rowRecord) {
      this.ruleForm = _.cloneDeep(rowRecord);

      this.getUserSourceList();
      this.accountSourceIds = [];
      for (const source of this.userSources) {
        if (source.sourceType === 'voucher') {
          continue;
        }
        this.accountSourceIds.push(source.sourceId);
      }

      rowRecord.areaList = rowRecord.areaList || [];
      this.areaIds = rowRecord.areaList.map((item) => {
        return item.id;
      });

      this.isVisible = true;
    },
    onClose() {
      this.activeKey = 1;
      this.isVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.btn-wrapper {
  display: flex;
  gap: 16px;
}
</style>
